# -*- coding:utf8 -*-
import cv2 as cv
from matplotlib import pyplot as plt
import numpy as np

def reverse(img):
    b, g, r = cv.split(img)
    return cv.merge([r, g, b])

img = cv.imread("images/song.jpg")
histo = cv.calcHist([img], [0], None, [256], [0, 256])
plt.figure(figsize=(3.5 * img.shape[0] * 0.01, 2.5 * img.shape[1] * 0.01))
plt.subplot(2, 3, 1), plt.title("Histo"), \
    plt.plot(histo), plt.xlabel("Gray Scale"), plt.ylabel("Pixel Num")

blur = cv.GaussianBlur(img, (3, 3), 0)
plt.subplot(2, 3, 2), plt.title("Gaussian Blur"), \
    plt.imshow(blur), plt.xticks([]), plt.yticks([])

blur = cv.medianBlur(blur, 3)

gray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY)
# cv.threshold(gray, 127, 255, cv.THRESH_BINARY, gray)
gray = cv.adaptiveThreshold(gray, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 3, 1)
gray = cv.medianBlur(gray, 3)
plt.subplot(2, 3, 3), plt.title("Histo"), \
    plt.imshow(gray, "gray"), plt.xlabel("Gray Scale"), plt.ylabel("Pixel Num")

_, contours, _ = cv.findContours(gray,
                                 cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for contour in contours:
    minRect = cv.minAreaRect(contour)
    box = cv.boxPoints(minRect)
    box = np.int0(box)

    cv.drawContours(blur, [box], 0, (0, 0, 255), 2)

plt.subplot(2, 3, 4), plt.title("Contours"), \
    plt.imshow(reverse(blur)), plt.xticks([]), plt.yticks([])

plt.show()

